# -*- coding: utf-8 -*-
# @Time : 2020/9/24 16:35
# @Author : HEAD
# @Email : scg@gmail.com
# @File : db.py
# @Project : scg_interface
"""
数据库链接，常用数据库方法封装
"""
import pymysql

from common.config import Config

c = Config()


from lib.config import Config

c = Config()

print(c.get_db_test('host'))


class DB:
    def __init__(self):
        self.conn = pymysql.connect(host=c.get_db_test('host'),
                                    port=int(c.get_db_test('port')),
                                    user=c.get_db_test('user'),
                                    passwd=c.get_db_test('passwd'),
                                    db=c.get_db_test('db'))
        self.cur = self.conn.cursor()

    def __del__(self):
        """析构函数，实例删除时自动触发"""
        self.cur.close()
        self.conn.close()

    def query(self, sql):
        """查询数据"""
        self.cur.execute(sql)
        return self.cur.fetchall()

    def exec(self, sql):
        """修改数据"""
        try:
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()

    def check_user(self, name):
        """检查用户是否已存在"""
        result = self.query("select * from user where name='{}'".format(name))
        return True if result else False

    def del_user(self, name):
        """删除用户"""
        self.exec("delete from user where name='{}'".format(name))

    def add_user(self, name, passwd):
        """添加用户"""
        self.exec("insert into user values('{}','{}')".format(name, passwd))


if __name__ == '__main__':
    db = DB()

    # print(db.query("select * from user"))

    print(db.query("select * from user"))

